const path = require('path');
const fs = require('fs');
const Base = require('./base.js');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.app = this.model('system/app');
		this.tactive = 'app';
	}
	/**
	 * index action
	 * @return {Promise} []
	 */
	async indexAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();

		let where = {};
		const data = await this.app.dataTable(posts, where);
		return this.json(data);
	}

	/**
	 * 添加应用
	 * @returns {*}
	 */
	async addAction() {
		if(this.isGet) {
			return this.display();
		}
		if(this.isPost) {
			const posts = this.post();
			posts.install_time = new Date().getTime();
			console.log(posts);
			let app = await this.app.where({
				code: posts.code
			}).find();
			console.log(app)
			if(!think.isEmpty(app)) {
				return this.fail("应用标识已存在");
			}
			await this.app.add(posts);
			
			return this.success("添加成功");
		}

	}

	/**
	 * 更新应用
	 * @returns {*}
	 */
	async editAction() {
		if(this.isPost) {
			const posts = this.post();

			const res = await this.app.where({
				id: posts.id
			}).update(posts);
			if(res) {
				return this.success('更新成功！');
			} else {
				return this.fail('更新失败！');
			}
		} else {
			const id = this.get('id');
			const app = await this.app.where({
				id: id
			}).find();
			this.assign('app', app);
			return this.display();
		}
	}

	async installAction() {

		let posts = this.post();
		let app = await this.app.findOne(posts.id);
		if(app.is_install) {
			return this.fail("应用已安装");
		}
		const appdir = `${think.ROOT_PATH}/src/controller/app`;
		const sqlpath = path.join(appdir, `${app.code}/${app.code}.sql`);
		if(think.isFile(sqlpath)) {
			const sqlfile = fs.readFileSync(sqlpath, 'utf8');
			// todo 自动适配表名
			// 导入数据库
			let content = sqlfile.split(/(?:\r\n|\r|\n)/g).filter(item => {
				item = item.trim();
				const ignoreList = ['--', 'SET', '#', 'LOCK', 'UNLOCK', 'INSERT'];
				for(const it of ignoreList) {
					if(item.indexOf(it) === 0) {
						return false;
					}
				}
				return true;
			}).join('');
			content = content.replace(/\/\*.*?\*\//g, '');
			content = content.substring(0, content.length - 1);
			// console.log(content);
			const arr = content.split(';');
			// console.log(arr);
			const insert = sqlfile.split(/(?:\r\n|\r|\n)/g).filter(item => {
				item = item.trim();
				if(item.indexOf('INSERT') === 0) {
					return true;
				}
				return false;
			});
			// console.log(insert);
			const sqlarr = arr.concat(insert);
			try {
				for(let item of sqlarr) {
					item = item.trim();
					if(item) {
						//          item = item.replace(/cmswing_/g, this.config('model.mysql.prefix') || '');
						think.logger.info(item);
						await this.model('mysql').execute(item);
					}
				}
			} catch(e) {
				think.logger.error(e);
				return this.fail('数据表导入失败');
			}
		}

		await this.app.setOne(app.id, {
			is_install: 1
		});
		return this.success("安装成功");

	}

	async uninstallAction() {
		let posts = this.post();
		let app = await this.app.findOne(posts.id);
		if(!app.is_install) {
			return this.fail("应用未安装");
		}
		

		if(!think.isEmpty(app.tables)) {
			await this.app.execute(`drop table ${app.tables}`);
		}

		await this.app.setOne(app.id, {
			is_install: 0
		});
		return this.success("卸载成功");

	}
	
	async setupAction(){
		
		if(this.isGet){
			let gets = this.get();
			let app = await this.app.findOne(gets.id);
			const confpath = `${think.ROOT_PATH}/src/controller/app/${app.code}/config.js`;
			const conffile = fs.readFileSync(confpath, 'utf8');
			this.assign("app",app);
			this.assign("conf",conffile);
			return this.display();
		}
		let posts = this.post();
		let app = await this.app.findOne(posts.id);
		const confpath = `${think.ROOT_PATH}/src/controller/app/${app.code}/config.js`;
		console.log(posts);
		fs.writeFileSync(confpath, posts.config);
		return this.success("更新成功");
		
	}

};